package com.gem.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/consumer")
@Slf4j
//配置默认降级
@DefaultProperties(defaultFallback = "defaultFallback")
public class UserController {

    @Autowired
    RestTemplate template;

    //@Autowired
    //DiscoveryClient discoveryClient;

    //localhost:8080/consumer/1
    @GetMapping("/{id}")
    //服务熔断,并且配置降级逻辑
    //@HystrixCommand(fallbackMethod = "queryByIdFallback")
    @HystrixCommand
    public String queryById(@PathVariable Long id) {
        //String url = "http://localhost:9092/user/" + id;

        //获取eureka中注册的user-service实例列表
        //List<ServiceInstance> list = discoveryClient.getInstances("user-service");
        // ServiceInstance serviceInstance = list.get(0);
        //String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/user/" + id;

        if (id == 1) {
            throw new RuntimeException("太忙了...");
        }
        String url = "http://user-service/user/" + id;
        return template.getForObject(url, String.class);
    }

    //降级逻辑代码
    //注意:降级逻辑代码方法返回类型和参数列表必须与映射方法保持一致
    public String queryByIdFallback(Long id) {
        log.error("查询用户信息失败。id：{}", id);
        return "对不起，网络太拥挤了！";
    }

    //全局降级处理策略
    public String defaultFallback() {
        return "全局降级: 对不起，网络太拥挤了！";
    }
}
